#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <strings.h>
#include <cstdlib>
// #include "Log.hpp"
using namespace  std;

class UdpServe
{
public:
    UdpServe(uint16_t port)
    :_sockefd(-1)
    ,_port(port)
    {}
    void Init()
    {
        //创建套接字
        _sockefd=socket(AF_INET,SOCK_DGRAM,0);
        if(_sockefd<0)
        {
            // LOG(LogLevel::FATAL)<<"create socket err";
            cout<<"create socket err";
            exit(-1);
        }
        // LOG(LogLevel::INFO)<<"create socket sucess";
         cout<<"create socket sucess";

        //填充ip,port
        struct sockaddr_in local;
        bzero(&local,sizeof(local));//初始化清0
        local.sin_family=AF_INET;
        local.sin_port=htons(_port);
        local.sin_addr.s_addr=htonl(INADDR_ANY);    //接收任意一个ip
        //进行bind
        int m=bind(_sockefd,(struct sockaddr*)&local,sizeof(local));
        if(m<0)
        {
            //  LOG(LogLevel::FATAL)<<"bind socket err";
             cout<<"bind socket err";

              exit(2);
        }
        // LOG(LogLevel::INFO)<<"bind socket sucess"<<_sockefd;
        cout<<"bind socket sucess"<<_sockefd;

    }
    void Start()
    {
        _isrunning=true;
        while(_isrunning)
        {
            struct sockaddr_in tmp; //获取客户端的ip和port
            bzero(&tmp,sizeof(tmp));
            socklen_t len=sizeof(tmp);
            char buffer[1024]={0};
            ssize_t n=recvfrom(_sockefd,buffer,sizeof(buffer),0,(struct sockaddr*)&tmp,&len);
            if(n>0)
            {
                buffer[n]=0;
                //注意：网络转主机
                uint16_t port=ntohs(tmp.sin_port);  //客户端的port
                string ip=inet_ntoa(tmp.sin_addr);  //客户端的ip
                // LOG(LogLevel::DEBUG)<<"["<<ip<<"]-"<<"["<<port<<"]"<<"say#"<<buffer<<_sockefd;
                cout<<"["<<ip<<"]-"<<"["<<port<<"]"<<"say#"<<buffer<<_sockefd;
            }
        }
    }
    void Stop()
    {
        _isrunning=false;
    }
    ~UdpServe()
    {}
private:
    //文件描述符
    int _sockefd;
    //ip
    // string _ip;
    //port
    uint16_t _port;
    bool _isrunning;
};


